package etcd

import (
	. "Go-Easy/pkg/config"
	"context"
	"fmt"
	clientv3 "go.etcd.io/etcd/client/v3"
	"go.etcd.io/etcd/client/v3/naming/endpoints"
	"log"
)

var etcdClient *clientv3.Client

//etcd中注册服务  参考 https://etcd.io/docs/v3.5/dev-guide/grpc_naming/
func EtcdRegistService(ServiceName string, ServiceTTL int64, addr string) error {
	log.Printf("etcd Register service [%s] at address[%s]\n", ServiceName, addr)
	etcdClient, err := clientv3.NewFromURL(ETCD.URL)
	if err != nil {
		return err
	}

	em, err := endpoints.NewManager(etcdClient, ServiceName)
	if err != nil {
		return err
	}

	//lease可以理解为存活周期
	lease, _ := etcdClient.Grant(context.TODO(), ServiceTTL)

	//添加终端
	err = em.AddEndpoint(context.TODO(), fmt.Sprintf("%s/%s", ServiceName, addr), endpoints.Endpoint{Addr: addr}, clientv3.WithLease(lease.ID))
	if err != nil {
		return err
	}

	//KeepAlive试图使给定的租约永远有效
	alive, err := etcdClient.KeepAlive(context.TODO(), lease.ID)
	if err != nil {
		return err
	}

	//如果alive,则do something
	go func() {
		for {
			<-alive
			//fmt.Println("etcd server keep alive")
		}
	}()

	return nil
}

//在etcd中撤销服务注册
func EtcdUnRegistService(ServiceName string, addr string) error {
	log.Printf("etcd UnRegister service [%s] at address [%s]\n", ServiceName, addr)
	if etcdClient != nil {
		em, err := endpoints.NewManager(etcdClient, ServiceName)
		if err != nil {
			return err
		}
		err = em.DeleteEndpoint(context.TODO(), fmt.Sprintf("%s/%s", ServiceName, addr))
		if err != nil {
			return err
		}
		return err
	}

	return nil
}
